package com.grape.interceptor;

import com.alibaba.fastjson.JSON;
import com.grape.utils.RequestUtils;
import com.grape.utils.StringUtils;
import com.grape.utils.ThreadLocalUtil;
import com.grape.vo.UserVO;
import jodd.util.Base64;
import org.slf4j.Logger;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author fuhehuang
 * @email 2628279194@qq.com
 */
public interface CommonThreadLocalInterceptor {

    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler, Logger logger) throws Exception {
        try {
            String base64 = RequestUtils.getToken(request);
            if (StringUtils.isBlank(base64)) return true;
            String s = new String(Base64.decode(base64));
            UserVO userVO = JSON.parseObject(new String(Base64.decode(base64)), UserVO.class);
            logger.info("当前线程获取用户信息 = " + userVO);
            ThreadLocalUtil.set(userVO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("当前线程获取用户信息失败: " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return true;
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex, Logger logger) throws Exception {
        ThreadLocalUtil.remove();
    }

}
